/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim</a>, 2005
 */
package hk.com.carfield.core;

import hk.com.carfield.item.Directory;
import hk.com.carfield.item.FileItem;
import hk.com.carfield.item.HeadItem;
import hk.com.carfield.item.Item;
import hk.com.carfield.util.LogUtil;
import hk.com.carfield.web.Request;

import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public final class ItemManager {
	public static Comparator<Item> getComparator(final Request req) {
		// TODO use req to handle user defined sorting
		return new Comparator<Item>() {
			public int compare(final Item item1, final Item item2) {
				if (item1 == null) {
					return -1;
				}
				if (item2 == null) {
					return 1;
				}
				final int itemClassComp = item1.getOrder() - item2.getOrder();
				if (itemClassComp != 0) {
					return itemClassComp;
				}
				final int dateComp = item2.getDate().compareTo(item1.getDate());
				if (dateComp != 0) {
					return dateComp;
				} else {
					return item1.getName().compareTo(item2.getName());
				}
			}
		};
	}

	public static Item getItem(final Context context, final File file) throws IOException {
		return FileItem.getFileItem(context, file, true);
	}

	public static Item getHeadItem(final Context context, final File file, final Request req, final int pageNo)
			throws IOException {
		if (file.isDirectory()) {
			return new Directory(context, file, req, pageNo);
		} else if (file.isFile()) {
			return new HeadItem(context, file);
		} else {
			if (!file.canRead()) {
				LogUtil.error(new Exception("ERROR: " + file + " is invalid"), context.mailMan, file, req);
			}
			return null;
		}

	}

	public static SortedSet<Item> getSortedSet() {
		final SortedSet<Item> itemSet = new TreeSet<Item>(getComparator(null));
		return itemSet;
	}
}